<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数 {{ total }}</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card>
        <!-- 列表表单 -->
        <el-table :default-sort="{ prop: 'timeOfEntry', order: 'ascending' }" border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 列表表单end -->

        <!-- 分页组件 -->
        <el-pagination
          class="pagination"
          :current-page="page"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 分页end -->
      </el-card>
      <el-dialog :title="isEdit ? '编辑员工' : '新增员工'" :visible.sync="showDialog" @close="resetForm">
        <addorEdit ref="addEmployees" @close="showDialog = false" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import addorEdit from './empDialog.vue'
import { getEmployees, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
// 获取枚举里面hireType的对象,并转换成{1:'正式',2:'非正式'}
// 这样循环,一次性获取数据之后,可以根据对象的键值对格式化数据,而不需要一直循环遍历数组对象去获取值,这样处理可以优化程序,性能提升,效率提高
// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// reduce用法
// const arr = [1, 2, 3]
// const num = arr.reduce((sum, item) => {
//   console.log('sum', sum)
//   return sum + item
// }, 0)
// console.log('num', num)
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  console.log('acc', acc)
  return acc
}, {})

console.log('hireType', hireType)

export default {
  name: 'Employees',
  components: { addorEdit },
  data() {
    return {
      isEdit: false,
      showDialog: false,
      total: 0,
      page: 1,
      size: 5,
      list: []
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    formData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出一个数据对象
      const one = list[0]
      // 判断one是否有值，如果没有直接终止程序
      if (!one) {
        //   list中没有数据
        return
      }
      console.log(Object.keys(one))
      // 使用对象生成需要的z中文header数据
      const header = Object.keys(one).map(enKey => {
        return map[enKey]
      })
      console.log(header)
      // 生产data函数
      const data = list.map(item => {
        const key = item.formOfEmployment
        item['formOfEmployment'] = hireType[key] || '未知'
        console.log(Object.values(item))
        return Object.values(item)
      })
      console.log(data)
      return { header, data }
    },
    async   handleDownload() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log(res.data.rows, 'res.data.rows')
        const { header, data } = this.formData(res.data.rows)
        //  import('@/vendor/Export2Excel')  懒加载的方式导入一个模块（文件）返回值是一个promise实例
        import('@/vendor/Export2Excel').then(excel => {
        // excel 指的是模块对象，可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量

          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除数据
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)

        // 重发请求
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) this.page = 1
        }
        this.loadEmployees()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },

    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => { })
    },
    // 重置表单
    resetForm() {
      this.$refs.addEmployees.resetForm()
    },
    // 添加/编辑成功后
    hSuccess() {
      // 1.计算出要跳转的页面数
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      // 2.重新渲染
      this.loadEmployees()
      // 3.关闭页面
      this.showDialog = false
    },
    // 新增功能
    hAdd() {
      this.showDialog = true
    },
    // 格式化聘用形式的函数
    formOfEmploymentFormat(data) {
      return hireType[data] || '未知'
    },
    // 发送请求获取员工列表数据,渲染页面
    async loadEmployees() {
      const { data: res } = await getEmployees(this.page, this.size)
      console.log('getEmployees', res)
      this.list = res.rows
      this.total = res.total
    },
    // 分页数据
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    }
  }
}
</script>
<style>
</style>
